import { ReqAddHospital, ReqGetHospitalSetItem, ReqUpdateHospital } from '@/api/hospitalSet/hospitalSet'
import { AddHospitalParams, HospitalItem } from '@/api/hospitalSet/model/hospitalSetTypes'
import { Button, Card, Form, Input, message } from 'antd'
import { useForm } from 'antd/lib/form/Form'
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'

export default function AddOrUpdateHospital() {

  //表单hook
  let [form] = useForm()

  //获取navigate 
  let navigate = useNavigate()

  // 获取地址栏的params参数
  let {id} = useParams()

  // 单个医院信息
  let [onehospital,setOneHospital] = useState<HospitalItem>()

  //提交表单方法
  let finish = async()=>{
    //获取表单数据
    let hospitalSet:AddHospitalParams = form.getFieldsValue()

    if (id) {
      await ReqUpdateHospital({
        ...hospitalSet,
        id
      })
      message.success("更新成功")
    } else {
      //调用方法请求添加医院
      await ReqAddHospital(hospitalSet)

      message.success("添加成功")
    }

    navigate(-1)
  }

useEffect(()=>{
  async function main() { 
    let result = await ReqGetHospitalSetItem(id as string)
    // console.log(result);
    setOneHospital(result)
    form.setFieldsValue(result)
  }
  main()  
},[])

  return (
    <Card>
      <Form
        form={form}
        onFinish={finish}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 20 }}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: '请输入医院名称！' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: '请输入医院编号!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: '请输入api基础路径!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[
            { required: true, message: '请输入联系人姓名!' },
            {
              pattern: /^[\u4e00-\u9fa5]{0,}$/, message: "请输入正确的联系人姓名"
            }
          ]}
        >
          <Input />
        </Form.Item>


        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: '请输入联系人手机号码!' },
            {
              pattern: /^1([358][0-9]|4[456789]|6[67]|7[0135678]|9[1589])\d{8}$/, message: "请输入正确的手机号码"
            }
          ]}
        >
          <Input />
        </Form.Item>



        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>

          <Button type="default" className='ml' onClick={()=>{
            navigate(-1)
          }}>
            返回
          </Button>
        </Form.Item>
      </Form>
    </Card>
  )
}
